'use strict';

const db = uniCloud.database()
const postsCollection = db.collection('community_posts')

exports.main = async (event, context) => {
	//event为客户端上传的参数
	const { action, data } = event
	
	// 获取用户信息
	const uniIDInstance = uniCloud.importObject("uni-id-co", {
		customUI: true
	})
	const currentUser = await uniIDInstance.checkToken(event.uniIdToken)
	if (currentUser.errCode) {
		return {
			code: currentUser.errCode,
			msg: currentUser.errMsg
		}
	}
	
	const userId = currentUser.uid
	
	// 根据action执行不同操作
	switch (action) {
		// 获取帖子列表
		case 'getPosts': {
			const { page = 1, pageSize = 10 } = data
			const skip = (page - 1) * pageSize
			
			try {
				// 获取总数
				const countResult = await postsCollection.count()
				const total = countResult.total
				
				// 获取帖子列表（按创建时间倒序）
				const res = await postsCollection
					.orderBy('created_at', 'desc')
					.skip(skip)
					.limit(pageSize)
					.get()
					
				return {
					code: 0,
					msg: '获取成功',
					data: {
						posts: res.data,
						pagination: {
							total,
							pageSize,
							current: page,
							pages: Math.ceil(total / pageSize)
						}
					}
				}
			} catch (e) {
				console.error('获取帖子列表失败', e)
				return {
					code: 500,
					msg: '获取帖子列表失败：' + e.message
				}
			}
		}
		
		// 获取单个帖子详情
		case 'getPostDetail': {
			const { id } = data
			if (!id) {
				return {
					code: 400,
					msg: '缺少帖子ID'
				}
			}
			
			try {
				const res = await postsCollection.doc(id).get()
				if (res.data && res.data.length > 0) {
					return {
						code: 0,
						msg: '获取成功',
						data: res.data[0]
					}
				} else {
					return {
						code: 404,
						msg: '帖子不存在'
					}
				}
			} catch (e) {
				console.error('获取帖子详情失败', e)
				return {
					code: 500,
					msg: '获取帖子详情失败：' + e.message
				}
			}
		}
		
		// 创建新帖子
		case 'createPost': {
			const { title, content, images, tags, location } = data
			
			if (!title || !content) {
				return {
					code: 400,
					msg: '标题和内容不能为空'
				}
			}
			
			const postData = {
				title,
				content,
				images: images || [],
				tags: tags || [],
				location: location || '',
				user_id: userId,
				comments: [],
				created_at: new Date(),
				updated_at: new Date()
			}
			
			try {
				const res = await postsCollection.add(postData)
				return {
					code: 0,
					msg: '发布成功',
					data: {
						id: res.id,
						...postData
					}
				}
			} catch (e) {
				console.error('发布帖子失败', e)
				return {
					code: 500,
					msg: '发布帖子失败：' + e.message
				}
			}
		}
		
		// 更新帖子
		case 'updatePost': {
			const { id, title, content, images, tags, location } = data
			
			if (!id) {
				return {
					code: 400,
					msg: '缺少帖子ID'
				}
			}
			
			try {
				// 先检查帖子是否存在且属于当前用户
				const checkRes = await postsCollection.doc(id).get()
				if (!checkRes.data || checkRes.data.length === 0) {
					return {
						code: 404,
						msg: '帖子不存在'
					}
				}
				
				const post = checkRes.data[0]
				if (post.user_id !== userId) {
					return {
						code: 403,
						msg: '无权限修改此帖子'
					}
				}
				
				// 更新帖子内容
				const updateData = {}
				if (title !== undefined) updateData.title = title
				if (content !== undefined) updateData.content = content
				if (images !== undefined) updateData.images = images
				if (tags !== undefined) updateData.tags = tags
				if (location !== undefined) updateData.location = location
				updateData.updated_at = new Date()
				
				const res = await postsCollection.doc(id).update(updateData)
				
				return {
					code: 0,
					msg: '更新成功',
					data: {
						...post,
						...updateData
					}
				}
			} catch (e) {
				console.error('更新帖子失败', e)
				return {
					code: 500,
					msg: '更新帖子失败：' + e.message
				}
			}
		}
		
		// 删除帖子
		case 'deletePost': {
			const { id } = data
			
			if (!id) {
				return {
					code: 400,
					msg: '缺少帖子ID'
				}
			}
			
			try {
				// 先检查帖子是否存在且属于当前用户
				const checkRes = await postsCollection.doc(id).get()
				if (!checkRes.data || checkRes.data.length === 0) {
					return {
						code: 404,
						msg: '帖子不存在'
					}
				}
				
				const post = checkRes.data[0]
				if (post.user_id !== userId) {
					return {
						code: 403,
						msg: '无权限删除此帖子'
					}
				}
				
				// 删除帖子
				await postsCollection.doc(id).remove()
				
				return {
					code: 0,
					msg: '删除成功'
				}
			} catch (e) {
				console.error('删除帖子失败', e)
				return {
					code: 500,
					msg: '删除帖子失败：' + e.message
				}
			}
		}
		
		// 添加评论
		case 'addComment': {
			const { postId, text } = data
			
			if (!postId || !text) {
				return {
					code: 400,
					msg: '缺少必要参数'
				}
			}
			
			try {
				// 获取用户信息
				const userRes = await db.collection('uni-id-users').doc(userId).field({
					nickname: 1
				}).get()
				
				if (!userRes.data || userRes.data.length === 0) {
					return {
						code: 404,
						msg: '用户信息获取失败'
					}
				}
				
				const username = userRes.data[0].nickname || '匿名用户'
				
				// 新评论
				const comment = {
					id: Date.now().toString(),
					user_id: userId,
					user_name: username,
					text,
					created_at: new Date()
				}
				
				// 更新帖子评论列表
				await postsCollection.doc(postId).update({
					comments: db.command.push([comment])
				})
				
				return {
					code: 0,
					msg: '评论成功',
					data: comment
				}
			} catch (e) {
				console.error('添加评论失败', e)
				return {
					code: 500,
					msg: '添加评论失败：' + e.message
				}
			}
		}
		
		// 点赞/取消点赞
		case 'toggleLike': {
			const { postId } = data
			
			if (!postId) {
				return {
					code: 400,
					msg: '缺少帖子ID'
				}
			}
			
			try {
				// 检查帖子是否存在
				const checkRes = await postsCollection.doc(postId).get()
				if (!checkRes.data || checkRes.data.length === 0) {
					return {
						code: 404,
						msg: '帖子不存在'
					}
				}
				
				const post = checkRes.data[0]
				const liked_by = post.liked_by || []
				const isLiked = liked_by.includes(userId)
				
				// 如果已点赞，则取消点赞；否则添加点赞
				let updateCmd
				if (isLiked) {
					updateCmd = {
						likes: db.command.inc(-1),
						liked_by: db.command.pull(userId)
					}
				} else {
					updateCmd = {
						likes: db.command.inc(1),
						liked_by: db.command.addToSet(userId)
					}
				}
				
				await postsCollection.doc(postId).update(updateCmd)
				
				return {
					code: 0,
					msg: isLiked ? '取消点赞成功' : '点赞成功',
					data: {
						isLiked: !isLiked
					}
				}
			} catch (e) {
				console.error('操作点赞失败', e)
				return {
					code: 500,
					msg: '操作点赞失败：' + e.message
				}
			}
		}
		
		default:
			return {
				code: 400,
				msg: '未知操作类型'
			}
	}
}; 